<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>放大镜效果</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    .box1 {
        width: 200px;
        height: 140px;
        margin: 100px;
        position: relative;
    }

    .box1 span {
        display: none;
        width: 100px;
        height: 70px;
        background-color: blueviolet;
        opacity: 0.5;
        position: absolute;
        left: 0px;
        top: 0;
        /* cursor: pointer; */
    }

    .box1 img {
        width: 200px;
        height: 140px;

    }

    .box2 {
        display: none;
        width: 400px;
        height: 280px;
        overflow: hidden;
        position: absolute;
        left: 310px;
        top: 100px;
    }

    .box2 img {
        width: 800px;
        height: 560px;
        position: relative;
        left: 0;
        top: 0;
    }
</style>

<body>
    <div class="box1">
        <span></span>
        <img src="imgs/001.jpg" alt="">
    </div>
    <div class="box2"><img src="imgs/001.jpg" alt=""></div>
</body>
<script>
    var box1 = document.querySelector('.box1')
    var box2 = document.querySelector('.box2')
    var sp = document.querySelector('.box1>span')
    var img = document.querySelector('.box2>img')
    // console.log(sp);

    var l = sp.offsetLeft;
    var t = sp.offsetTop;
    console.log(l, t);
    box1.onmouseenter = function (e) {
        sp.style.display = 'block'
        box2.style.display = 'block'
    }
    box1.onmouseleave = function () {
        // box1.onmousemove = null
        sp.style.display = 'none'
        box2.style.display = 'none'
    }



    this.onmousemove = function (e) {

        var x = e.pageX - box1.offsetLeft - sp.offsetLeft / 2;
        var y = e.pageY - box1.offsetTop - sp.offsetTop / 2;


        var maxx = box1.offsetWidth - sp.offsetWidth;
        var maxy = box1.offsetHeight - sp.offsetHeight;
        if (x <= 0) {
            x = 0;
        } else if (x >= maxx) {
            x = maxx;
        }
        sp.style.left = x + 'px';

        if (y <= 0) {
            y = 0;
        } else if (y >= maxy) {
            y = maxy;
        }
        sp.style.top = y + 'px';


        // 大图

        // 4 的计算  倍率
        // var blx = (box2.offsetWidth - img.offsetWidth)/maxx

        img.style.left = -4 * x + 'px'
        img.style.top = -4 * y + 'px'

    }

</script>

</html>